﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Diagnostics;
using BrainTechLLC.ThreadSafeObjects;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	public class TimeMethodWrapper : AroundMethodBase, IAroundInvoke
	{
		public readonly static ThreadSafeLookupOnDemand<string, Stopwatch> WatchLookup = new ThreadSafeLookupOnDemand<string, Stopwatch>();

		protected override void Execute(IInvocationContext context, CutpointType when, object returnValue)
		{
			object thisObject = context.Target;
			TimeMethodAttribute[] attrs = context.TargetMethod.ReadAttribute<TimeMethodAttribute>();
			
			if (attrs != null && attrs.Length > 0)
			{
				string watchKey = context.CallingMethod.Name + context.TargetMethod.Name;

				for (int n = 0; n < attrs.Length; n++)
				{
					TimeMethodAttribute attr = attrs[n];
					if (when == CutpointType.Before)
					{
						Stopwatch watch = WatchLookup.Get(watchKey);												
						watch.Start();						
					}
					else
					{
						Stopwatch watch = WatchLookup.Get(watchKey);
						watch.Stop();
						attr.DoWorkAfter(context, thisObject, watch);
						watch.Reset();
					}
				}
			}
		}
	}
}

